<template>
  <x-dialog :title="title" :show.sync="visible" v-if="visible" :before-close="handleClose" width="60%">
    <el-form :model="params" :rules="rules" ref="params" class="demo-form-inline" label-position="top">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item :label="$t('config.agreement.name')" prop="agreementName">
            <el-input
              v-model="params.agreementName"
              :placeholder="$t('config.agreement.namePlaceholder')"
              clearable
              maxlength="20"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('config.agreement.code')" prop="agreementCode">
            <el-input
              v-model="params.agreementCode"
              :placeholder="$t('config.agreement.codePlaceholder')"
              clearable
              maxlength="20"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('config.agreement.type')" prop="agreementType">
            <x-select
              :placeholder="$t('config.agreement.typePlaceholder')"
              v-model="params.agreementType"
              :options="dictOptions['tc_agreement.agreement_type']"
              style="width: 100%"
            ></x-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('config.agreement.state')" prop="state">
            <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('config.agreement.descir')" prop="remark">
            <el-input
              v-model="params.remark"
              :placeholder="$t('config.agreement.descirPlaceholder')"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 8 }"
              clearable
              maxlength="200"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('config.agreement.content')" prop="agreementContext">
            <!-- 此处待处理富文本插入图片带有token的问题 -->
            <x-editor v-model="params.agreementContext" :excludeMenuKeys="['uploadImage', 'uploadVideo']"></x-editor>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('config.agreement.files')">
            <x-upload
              ref="fileUpload"
              :edit-flag="true"
              :limit="9"
              :fileSize="20"
              :old-file-list="params.tcAgreementFileVoList"
              :file-type="['jpg', 'jpeg', 'png', 'ppt', 'pptx', 'pdf', 'xls', 'xlsx']"
            >
            </x-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button
        type="primary"
        @click="
          loading = true
          handleSubmit()
        "
        :loading="loading"
      >
        {{ $t('common.save') }}
      </el-button>
    </span>
  </x-dialog>
</template>
<script>
  import { cloneDeep, omit, throttle, vaildEditor } from '@package/utils'
  import { EnumApiCode } from '../../../../../../globalEnum'
  import { apiPostCreatAgreement, apiPostUpdateAgreement } from '../api/agreement.js'

  export default {
    name: 'AgreementDialog',
    props: {
      dictOptions: {
        type: Object
      }
    },
    data() {
      return {
        visible: false,
        loading: false,
        title: this.$t('config.agreement.new'),
        params: {
          agreementName: '',
          agreementCode: '',
          agreementType: '',
          remark: '',
          agreementContext: '',
          state: '1',
          tcAgreementFileDtos: []
        },
        rules: {
          agreementName: [{ required: true, message: this.$t('config.agreement.namePlaceholder'), trigger: 'blur' }],
          agreementCode: [{ required: true, message: this.$t('config.agreement.codePlaceholder'), trigger: 'blur' }],
          agreementType: [{ required: true, message: this.$t('config.agreement.typePlaceholder'), trigger: 'blur' }],
          agreementContext: [
            { required: true, message: this.$t('config.agreement.contentPlaceholder'), trigger: 'blur' },
            { validator: this.validateEditorText, trigger: 'blur' }
          ],
          state: [{ required: true, message: '请选择状态', trigger: 'blur' }]
        }
      }
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        if (info?.id) {
          this.title = this.$t('common.edit')
          const times = setTimeout(() => {
            this.params = Object.assign(this.params, cloneDeep(info))
            this.params.state += ''
            clearTimeout(times)
          })
          return
        }
        this.title = this.$t('config.agreement.new')
      },
      handleSubmit: throttle(function () {
        this.loading = true
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const param = {
              ...this.params,
              tcAgreementFileDtos: this.$refs.fileUpload.fileList.map((v) => {
                return {
                  fileName: v.name || v.fileName,
                  filePath: v.filePath || v.response.data.filePath,
                  fileType: (v.name || v.fileName).slice((v.name || v.fileName).lastIndexOf('.') + 1),
                  remark: v.remark
                }
              })
            }
            try {
              const { code, msg } = this.params.id
                ? await apiPostUpdateAgreement(param)
                : await apiPostCreatAgreement(param)
              this.loading = false
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.handleClose()
                this.$emit('handleSuccess')
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.loading = false
            }
          } else {
            this.loading = false
            return false
          }
        })
      }, 1000),
      handleClose() {
        this.$refs.params.resetFields()
        this.params = omit(this.params, 'id')
        this.loading = false
        this.visible = false
      },
      validateEditorText(rule, value, callback) {
        if (value && value !== '' && vaildEditor(value)) {
          callback(new Error(this.$t('config.agreement.contentPlaceholder')))
        } else {
          callback()
        }
      }
    }
  }
</script>
